package com.gclife;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;

import javax.servlet.http.HttpServletRequest;

/**
 * 添加统一的请求过滤：
 * 1. 对所有请求检查是否有 Authorization 头
 * 2. 对于鉴权服务，只允许 password & refresh_token 请求通过
 */
public class AccessFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();

        Object authorization = request.getHeader("Authorization");
        if (authorization == null) {
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(401);
            return null;
        }

        Object grantType = request.getParameter("grant_type");
        String requestURI = request.getRequestURI();
        if (requestURI.equals("/uaa/oauth/token")
                && (!grantType.equals("refresh_token") && !grantType.equals("password"))) {
            // TODO 暂时注释
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(401);
            return null;
        }

        return null;
    }
}
